<template>
  <view class="container">
    <view class="avatar-box">
      <view class="click" @click="chooseAvatar">
        <u-avatar :src="user.avatar" size="140"></u-avatar>
        <text class="text">修改头像</text>
      </view>
    </view>
    <div class="form">
      <u-form :model="user" ref="uForm">
        <u-form-item label="昵称" prop="user_nickname"><u-input v-model="user.user_nickname" placeholder="请输入昵称" /></u-form-item>
        <u-form-item label="性别">
          <u-radio-group v-model="sex">
            <u-radio v-for="(item, index) in sexList" :key="index" :name="item.name">
			{{ item.name }}
			</u-radio>
          </u-radio-group>
        </u-form-item>
        <u-form-item label="生日">
          <u-input type="select" :select-open="birthdayShow" v-model="user.birthday" placeholder="请选择生日" @click="birthdayShow = true"></u-input>
        </u-form-item>
        <u-form-item label="签名" prop="signature"><u-input v-model="user.signature" placeholder="请输入个性签名" /></u-form-item>
      </u-form>
      <div class="btn"><u-button @click="submit">提交</u-button></div>
    </div>
    <u-picker mode="time" v-model="birthdayShow" :default-time="user.birthday" @confirm="confirmBirthday"></u-picker>
    <u-toast ref="uToast" />
  </view>
</template>

<script>
import { mapState } from 'vuex';
export default {
  computed: {
    ...mapState(['user'])
  },
  watch: {
    sex(val) {
      this.user.sex = val === '保密' ? 0 : val === '男' ? 1 : 2;
    }
  },
  data() {
    return {
      rules: {
        user_nickname: [{ required: true, message: '请输入昵称', trigger: ['blur', 'change'] }],
        signature: [{ min: 5, message: '签名不能少于5个字', trigger: ['blur', 'change'] }]
      },
      sex: '',
      sexList: [{ name: '保密' }, { name: '男' }, { name: '女' }],
      birthdayShow: false,
      loading: false
    };
  },
  onLoad() {
    this.onAvatarCropper(); // 监听头像裁剪返回结果
    // 性别判断  0：保密  1：男  2：女
    this.sex = this.user.sex === 0 ? '保密' : this.user.sex === 1 ? '男' : '女';
    // 生日初始值
    if (!this.user.birthday) {
      this.user.birthday = '2000-01-01';
    }
  },
  onReady() {
    // 初始化表单提醒规则
    this.$refs.uForm.setRules(this.rules);
  },
  methods: {
    // 头像裁剪
    chooseAvatar() {
      this.$u.route({
        url: '/uview-ui/components/u-avatar-cropper/u-avatar-cropper',
        params: {
          // 输出图片宽度，高等于宽，单位px
          destWidth: 140,
          // 裁剪框宽度，高等于宽，单位px
          rectWidth: 140,
          // 输出的图片类型，如果'png'类型发现裁剪的图片太大，改成"jpg"即可
          fileType: 'jpg'
        }
      });
    },
    // 上传头像，修改用户信息
    onAvatarCropper() {
      let that = this;
      uni.$on('uAvatarCropper', path => {
        that.$api.uploadFile({
          url: 'user/upload/avatar',
          filePath: path,
          name: 'file',
          success: resFile => {
            if (resFile.code == 1) {
              that.$api.post({
                url: 'user/profile/userInfo',
                data: {
                  avatar: resFile.data.filepath
                },
                success: res => {
                  if (res.code == 1) {
                    that.user.avatar = resFile.data.url;
                    that.$store.commit('updateUserInfo', that.user); // 保存变更信息
                    that.$refs.uToast.show({
                      title: res.msg,
                      type: 'success'
                    });
                  } else {
                    that.$refs.uToast.show({
                      title: res.msg,
                      type: 'error'
                    });
                  }
                }
              });
            } else {
              that.$refs.uToast.show({
                title: res.msg,
                type: 'error'
              });
            }
          }
        });
      });
    },
    // 选择生日
    confirmBirthday(e) {
      this.user.birthday = `${e.year}-${e.month}-${e.day}`;
    },
    // 提交表单
    submit() {
      if (this.user.user_nickname == '') {
        this.$refs.uToast.show({
          title: '请输入昵称',
          type: 'warning'
        });
        return;
      }
      if (this.loading) {
        return;
      }
      this.loading = true;
      this.$api.post({
        url: 'user/profile/userInfo',
        data: {
          user_nickname: this.user.user_nickname,
          birthday: this.user.birthday,
          sex: this.user.sex,
          signature: this.user.signature
        },
        success: res => {
          if (res.code == 1) {
            this.$store.commit('updateUserInfo', this.user); // 保存变更信息
            this.$refs.uToast.show({
              title: res.msg,
              type: 'success',
              callback: () => {
                this.$u.route({
                  type: 'back'
                });
              }
            });
          } else {
            this.$refs.uToast.show({
              title: res.msg,
              type: 'error'
            });
          }
        },
        complete: () => {
          this.loading = false;
        }
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.avatar-box {
  display: flex;
  justify-content: center;
  height: 300rpx;
  .click {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
  }
  .text {
    font-size: 26rpx;
    color: #999999;
    margin-top: 10rpx;
  }
}
.form {
  background: #ffffff;
  padding: 0 20rpx;
  .btn {
    padding: 40rpx 0;
  }
}
</style>
